package com.lishem.leftgod.level1.class03;

import java.util.HashMap;
import java.util.Map;

public class Code_06_RandomPool {


    public static class Pool<T> {
        Map<T, Integer> valueIndexMap;
        Map<Integer, T> indexValueMap;
        int index;

        public Pool() {
            this.valueIndexMap = new HashMap<>();
            this.indexValueMap = new HashMap<>();
            index = 0;
        }

        public void insert(T key) {
            if (valueIndexMap.containsKey(key)) {
                return;
            }
            valueIndexMap.put(key, index);
            indexValueMap.put(index++, key);
        }

        public void delete(T key) {
            if (!valueIndexMap.containsKey(key)) {
                return;
            }
            Integer deleteIndex = valueIndexMap.remove(key);
            indexValueMap.remove(deleteIndex);
            // 最后一个位置的key拿出来
            T tmp = indexValueMap.get(--index);
            valueIndexMap.put(tmp, deleteIndex);
            indexValueMap.put(deleteIndex, tmp);
        }

        public T getRandom() {
            return indexValueMap.get((int)(Math.random() * index));
        }

    }

    public static void main(String[] args) {
        Pool<String> pool = new Pool<>();
        pool.insert("zuo");
        pool.insert("cheng");
        pool.insert("yun");
        pool.insert("da");
        pool.insert("lao");
        pool.delete("yun");
        System.out.println(pool.getRandom());
        System.out.println(pool.getRandom());
        System.out.println(pool.getRandom());
        System.out.println(pool.getRandom());
        System.out.println(pool.getRandom());
        System.out.println(pool.getRandom());
    }
}
